﻿using SmallJob.Model;
using SmallJob.Services.Code;
using SmallJob.Services.Interfaces;
using SmallShop.Services.Implements;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace BackEnd.Controllers
{
    [Authorize]
    public class ProvideController : Controller
    {
        private readonly IProvideService _ProvideService;
        private readonly IUserService _UserService;
        private readonly ICategoryService _CategoryService;
        public ProvideController(IProvideService ProvideService, IUserService UserService, ICategoryService CategoryService)
        {
            _ProvideService = ProvideService;
            _UserService = UserService;
            _CategoryService = CategoryService;
        }
        //
        // GET: /Provide/

        public ActionResult Index(string page, string filter)
        {
            if (string.IsNullOrWhiteSpace(page))
            {
                page = "1";
            }
            ViewData["tableindex"] = new { page = page, pagesize = Convert.ToInt32(Resources.Resource.ItemPerPage), filter = filter };
            return View();
        }
        public ActionResult Details(int id)
        {
            var model = _ProvideService.GetById(id);
            model.User = _UserService.GetById(model.UserID);
            model.Category = _CategoryService.GetById(model.CategoryID);
            return View(model);
        }
        [HttpPost]
        public ActionResult Hidden(int id)
        {
            try
            {
                var provide = _ProvideService.GetById(id);
                provide.IsDeleted = true;
                _ProvideService.Update(provide);
                return Json(true);
            }
            catch (Exception)
            {

                return Json(false);
            }
        }
        [HttpPost]
        public ActionResult UnHidden(int id)
        {
            try
            {
                var provide = _ProvideService.GetById(id);
                provide.IsDeleted = false;
                _ProvideService.Update(provide);
                return Json(true);
            }
            catch (Exception)
            {

                return Json(false);
            }
        }
        public ActionResult TableProvide(int page, int pagesize, string filter)
        {
            int total = 0;
            pagesize = Convert.ToInt32(Resources.Resource.ItemPerPage);
            if (page == 0)
            {
                page = 1;
            }
            var model = _ProvideService.GetByPage(page, pagesize, out total);
            if (!string.IsNullOrWhiteSpace(filter))
            {
                model = _ProvideService.GetByPageFilter(page, pagesize, out total, filter);
                ViewData["filter"] = filter;
            }
            model = UtilityService.ProvideLoadUser(model, _UserService);
            model = UtilityService.ProvideLoadCategory(model, _CategoryService);
            if ((total % pagesize) > 0)
            {
                ViewData["total"] = (total / pagesize) + 1;
            }
            else
            {
                ViewData["total"] = total / pagesize;
            }
            ViewData["curpage"] = page;
            ViewData["nextpage"] = page + 1;
            ViewData["prepage"] = page - 1;
            return PartialView(model);
        }
        public ActionResult SearchByTitle(string s)
        {
            var list = _ProvideService.Find(s);
            List<Object> result = new List<object>();
            foreach (var item in list)
            {
                result.Add(new { id = item.ID, title = item.Title, owner = _UserService.GetById(item.UserID).ProperName });
            }
            return Json(result);
        }
        public ActionResult GetByID(int id, int fiid)
        {
            var item = _ProvideService.GetById(id);
            return Json(new { id = item.ID, title = item.Title, owner = _UserService.GetById(item.UserID).ProperName, fiid = fiid });
        }
        public ActionResult Add()
        {
            int id = 0;
            try
            {
                id = Convert.ToInt32(RouteData.Values["id"]);
            }
            catch
            {
                id = 0;
            }
            var request = _ProvideService.GetById(id);
            if (request == null)
            {
                request = new Provide()
                {
                    ID = 0,
                    DescriptionOrder = "",
                    DescriptionPay = "",
                    Price = 0,
                    Title = "",
                    Location = ""
                };
            }
            ViewData["AllCate"] = _CategoryService.All();
            return View(request);
        }
        [ValidateInput(false)]
        public ActionResult Save(IEnumerable<HttpPostedFileBase> imgs, HttpPostedFileBase file, List<String> oldImg, string description)
        {
            int id = Convert.ToInt32(Request.Form["id"]);
            var provide = _ProvideService.GetById(id);
            if (provide == null)
                provide = new Provide()
                {
                    ID = 0,
                    CreatedDate = DateTime.Now,
                    Price = 0
                };
            provide.Title = Request.Form["title"];
            provide.Location = Request.Form["location"];
            provide.CategoryID = Convert.ToInt32(Request.Form["cateID"]);
            provide.DescriptionOrder = HttpUtility.HtmlEncode(description);
            provide.DescriptionPay = "";
            //provide.DescriptionPay = Request.Form["DesPay"];
            provide.ModifiedDate = DateTime.Now;
            var u = _UserService.GetById(provide.UserID);
            provide.SkillID = Convert.ToInt32(Request.Form["skillID"]);
            try
            {
                provide.Price = Convert.ToInt32(Request.Form["price"]) * 1000;
            }
            catch
            {
                ModelState.AddModelError("PriceInvalid", "Nhập Đúng Giá");
            }
            try
            {
                provide.TimeToComplete = Convert.ToInt32(Request.Form["complete"]);
            }
            catch
            {
                ModelState.AddModelError("Time Complete Invalid", "Thời gian để hoàn thành, nhập số nguyên theo ngày.");
            }
            if (string.IsNullOrWhiteSpace(provide.Title))
                ModelState.AddModelError("TitleInvalid", "Tiêu đề không được bỏ trông");
            if (string.IsNullOrWhiteSpace(provide.Location))
                ModelState.AddModelError("LocationInvalid", "Địa điểm không được bỏ trông");
            if (string.IsNullOrWhiteSpace(provide.DescriptionOrder))
                ModelState.AddModelError("DescriptionOrderInvalid", "Nội dung không được bỏ trông");
            provide.ImagePath = "";

            //upload delivery
            if (file != null && file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                fileName = UploadHelper.GetNamePlusDatetime(fileName, true);
                var path = Path.Combine(UploadHelper.GetPathSaveFile(u.ID), fileName);
                if (file.ContentLength > (1024 * 1024 * 200))
                {
                    ModelState.AddModelError("FileInvalid", "Dung lượng của tập tin vượt quá cho phép.");
                }
                else
                {
                    file.SaveAs(path);
                    provide.IsDeliveryImmediate = true;
                    provide.Download = fileName;
                }
            }
            if (provide != null)
            {
                if (Request.Form["deliveryimmediate"] != null)
                {
                    provide.IsDeliveryImmediate = true;
                }
                else
                {
                    provide.IsDeliveryImmediate = false;
                }
            }
            if (oldImg != null)
            {
                foreach (var item in oldImg)
                {
                    provide.ImagePath += item + ";";
                }
            }
            if (imgs != null)
            {
                foreach (var img in imgs)
                {
                    if (img != null && img.ContentLength != 0)
                    {
                        DateTime dt = DateTime.Now;
                        // extract only the fielname
                        var fileName = Path.GetFileName(img.FileName);
                        // upload anh vao folder
                        var path = Path.Combine(UserUtility.GetFolderProvideUpload() + u.ID, dt.ToBinary() + "_" + fileName);
                        if (!Directory.Exists(UserUtility.GetFolderProvideUpload() + u.ID))
                        {
                            Directory.CreateDirectory(UserUtility.GetFolderProvideUpload() + u.ID);
                        }
                        img.SaveAs(path);
                        provide.ImagePath += UserUtility.GetImageProvideUpload() + u.ID + "/" + dt.ToBinary() + "_" + fileName + ";";
                        ;
                    }
                }
            }
            //image

            if (ModelState.IsValid)
            {
                if (provide.ID == 0)
                {
                    _ProvideService.Add(provide);
                    TempData["mess"] = "Thêm thành công!";
                    return RedirectToAction("Add");
                }
                else
                {
                    _ProvideService.Update(provide);
                    TempData["mess"] = "Sửa thành công!";
                    return RedirectToAction("Add", new { id = provide.ID });
                }
            }
            ViewData["AllCate"] = _CategoryService.All();
            return View("Add", provide);
        }
    }
}
